Adapter
Allows objects with incompatible interfaces to work together by wrapping one of the objects with an adapter that performs the necessary conversions.
Structure
Target Interface: This is the interface that the client expects and uses.Adaptee: This is the class with an incompatible interface that needs to be adapted.Adapter: This class implements the target interface and wraps the adaptee. It translates the requests from the client into the method calls that are understood by the adaptee.Client: The client interacts with the system using the target interface, unaware that an adapter is being used behind the scenes.
Example
// Target interface
interface MediaPlayer {
void play(String audioType, String fileName);
}
// Adaptee
class VLCPlayer {
public void playVLC(String fileName) {
System.out.println("Playing VLC file: " + fileName);
}
}
// Adapter
class MediaAdapter implements MediaPlayer {
private VLCPlayer vlcPlayer;
public MediaAdapter() {
vlcPlayer = new VLCPlayer();
}
@Override
public void play(String audioType, String fileName) {
if (audioType.equalsIgnoreCase("vlc")) {
vlcPlayer.playVLC(fileName);
}
}
}
// Client
class AudioPlayer implements MediaPlayer {
private MediaAdapter mediaAdapter;
@Override
public void play(String audioType, String fileName) {
if (audioType.equalsIgnoreCase("vlc")) {
mediaAdapter = new MediaAdapter();
mediaAdapter.play(audioType, fileName);
} else {
System.out.println("Unsupported media type.");
}
}
}